<template>
  <div class="tz">
    <!-- 顶部 -->
    <div class="hd">
      <div class="xm">
        项目台账
      </div>
      <button class="xz" @click="handleDialogValue()">新增项目</button>
    </div>
    <!-- 搜索 -->
    <div class="ts">
      <div class="search">
        <el-input v-model="query.projectName" size="large" placeholder="输入项目名称" style="width: 475px; height: 50px;"
          :suffix-icon="Search" />
        <!-- 1 -->
        <el-select v-model="query.statusCategory" placeholder="请选择项目状态" clearable @change="handleStatusCategoryChange"
          style="margin-left: 25px; width: 251px; height: 50px;">
          <el-option label="全部" value=""></el-option>
          <el-option v-for="(label, value) in statusOptions" :key="value" :label="label" :value="value">
          </el-option>
        </el-select>

        <el-dropdown @command="handleProjectLeaderChange">
          <!-- 2 -->
          <el-button>
            项目负责人<el-icon class="el-icon--right">
              <CaretBottom />
            </el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="">全部</el-dropdown-item>
              <el-dropdown-item v-for="(item, index) in uniqueProjectLeaders" :key="index" :command="item">
                {{ item }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>

        <el-dropdown @command="handleProjectEmpIdChange">
          <!-- 3 -->
          <el-button>
            项目经理选择<el-icon class="el-icon--right">
              <CaretBottom />
            </el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="">全部</el-dropdown-item>
              <el-dropdown-item v-for="(item, index) in uniqueProjectEmpIds" :key="index" :command="item">
                {{ item }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>

        <el-dropdown @command="handleBusinessTypeChange">
          <!-- 4 -->
          <el-button>
            业务类型选择<el-icon class="el-icon--right">
              <CaretBottom />
            </el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="">全部</el-dropdown-item>
              <el-dropdown-item v-for="(item, index) in uniqueBusinessTypes" :key="index" :command="item">
                {{ item }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>


    <!-- 时间+查询 -->
    <div class="block">
      <div class="btime">
        <el-date-picker v-model="value1" type="date" placeholder="开始时间" style="width: 200px;
          height: 50px;" :default-value="new Date(2025, 6, 1)" />
        <el-date-picker v-model="value2" type="date" placeholder="结束时间" style="margin-left: 20px;width: 200px;
          height: 50px;" :default-value="new Date(2025, 6, 1)" />
      </div>
      <div class="bu">
        <el-button style="width: 120px;
        height: 40px;" class="time" @click="search">查 询</el-button>
        <el-button style="width: 120px;
        height: 40px;" class="time" @click="Expo">导 出</el-button>
        <el-button style="width: 120px;
        height: 40px;" class="time" @click="clearFilters">清 空</el-button>
      </div>
    </div>



    <!-- 表格 -->
    <div class="table">
      <el-table ref="multipleTableRef" :data="tableData" row-key="id" style="width: 100%;"
        :header-cell-style="{ backgroundColor: '#1A70AD' }">
        <el-table-column type="selection" width="55" />

        <el-table-column :property="item.property" :label="item.label" :width="item.width" sortable
          v-for="(item, index) in option" :key="index">
          <template #default="{ row }" v-if="item.property === 'action'">
            <div class="action">
              <el-button type="success" :icon="MoreFilled" circle @click="drawe(row)" />
              <!-- <el-button  type="primary" :icon="Position" circle @click="" /> -->
              <!-- <el-button  type="primary" :icon="Edit" circle @click="handleDialogValue(row)" />
            <el-button  type="danger" :icon="Delete" circle @click="Del(row)" /> -->
            </div>
          </template>

          <template #default="{ row }" v-if="item.property === 'statusCategory'">
            <el-tag :type="getStatusType(row.statusCategory)">
              {{ getStatusText(row.statusCategory) }}
            </el-tag>
          </template>


        </el-table-column>

      </el-table>
    </div>
    <!-- 分页 -->
    <div class="page">
      <el-pagination v-model:current-page="query.page" :page-size="query.size" :page-sizes="[5, 10, 20, 50]"
        layout="sizes,total, prev, pager, next" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>


    <!-- 抽屉详情 -->
    <el-drawer v-model="drawer" title="I am the title" :with-header="false" size="50%">
      <div class="detail">
        <div class="h">
          <div class="tit">数字化投资系统</div>
        </div>
        <div class="fle">
          <el-card style="max-width: 480px" shadow="hover">
            <div class="card">
              <div class="p">
                <p>业务类型 : {{ rowValue.businessType }}</p>
                <p>项目编号 : {{ rowValue.id }}</p>
                <p>项目名称 : {{ rowValue.projectName }}</p>
                <p>行业类别 : {{ rowValue.industryCategory }}</p>
                <p>法定代表人 : {{ rowValue.legalRepresentative }}</p>
                <p>联系人 : {{ rowValue.contact }}</p>
                <p>项目状态 : <el-tag :type="getStatusType(rowValue.statusCategory)">
                    {{ getStatusText(rowValue.statusCategory) }}
                  </el-tag>
                </p>
                <p>投资时间 : {{ rowValue.investmentDate }}</p>
                <p>项目经理 : {{ rowValue.projectEmpId }}</p>
                <p>项目负责人 : {{ rowValue.projectLeader }}</p>
              </div>
            </div>
          </el-card>
          <el-button type="primary" :icon="Position" @click="Requestqx(requestData)">
            请求权限
          </el-button>
        </div>
      </div>

    </el-drawer>


    <!-- 弹框 -->
    <Dialog v-model="dialogVisible" :dialogTitle="dialogTitle" v-if="dialogVisible" @initUserList="GetData"
      :dialogTableValue="dialogTableValue" />
  </div>
</template>

<script setup lang='ts'>
import { ref, onMounted } from 'vue'
import { Search, CaretBottom } from '@element-plus/icons-vue'
import { getData, onDelete, Export, getManagerId } from '@/api/project/search'
import {
  Delete,
  Edit,
  Position,
  MoreFilled,
} from '@element-plus/icons-vue'
import { option } from '@/api/project/option'
import Dialog from './components/dialog.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { toRaw } from 'vue'
import { Request } from '@/api/users/users'
import request from '@/utils/http'




const value1 = ref('')
const value2 = ref('')
const tableData = ref([])
const total = ref(0)
const query = ref({
  businessType: '',
  projectEmpId: '',
  projectName: '',
  statusCategory: '',
  projectLeader: '',  // 添加项目负责人字段
  createTime: '',
  investmentDate: '',
  page: 1,
  size: 5,
  sort: ''
})

const statusOptions = {
  0: '正常',
  1: '诉讼',
  2: '关注',
  3: '终止',
  4: '暂停'
}


//渲染
const GetData = async () => {
  const res = await getData(query.value)
  // console.log(res)
  if (res && res.data) {
    tableData.value = res.data.list || []
    total.value = res.data.total || 0
    // 获取唯一值用于下拉选项
    getUniqueValues()
  }
}
GetData()



//搜索
const search = async () => {
  // query.value.page = 1  // 搜索时重置到第一页

  const res = await getData(query.value)
  if (res && res.data) {
    tableData.value = res.data.list || []
    total.value = res.data.total || 0
  }
}

//导出
const Expo = async () => {
  try {
    const res = await Export();

    // 创建Blob对象
    const blob = new Blob([res], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    });

    // 创建下载链接
    const link = document.createElement('a');
    const url = window.URL.createObjectURL(blob);

    // 设置文件名（可以根据需要修改）
    link.href = url;
    link.download = '项目台账数据.xlsx';
    link.style.display = 'none';

    // 添加到页面并触发点击
    document.body.appendChild(link);
    link.click();

    // 清理
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

    ElMessage.success('导出成功');
  } catch (error) {
    console.error('导出失败:', error);
    ElMessage.error('导出失败');
  }
}
//清空
const clearFilters = () => {
  query.value.businessType = ''
  query.value.projectEmpId = ''
  query.value.projectName = ''
  query.value.statusCategory = ''
  query.value.projectLeader = ''
  query.value.createTime = ''
  query.value.page = 1
  search()
}





//下拉框

const uniqueStatusCategories = ref([])
const uniqueProjectLeaders = ref([])
const uniqueProjectEmpIds = ref([])
const uniqueBusinessTypes = ref([])

// 获取所有唯一值用于下拉选项
const getUniqueValues = () => {
  if (tableData.value && tableData.value.length > 0) {
    uniqueStatusCategories.value = [...new Set(tableData.value.map(item => item.statusCategory).filter(Boolean))]
    uniqueProjectLeaders.value = [...new Set(tableData.value.map(item => item.projectLeader).filter(Boolean))]
    uniqueProjectEmpIds.value = [...new Set(tableData.value.map(item => item.projectEmpId).filter(Boolean))]
    uniqueBusinessTypes.value = [...new Set(tableData.value.map(item => item.businessType).filter(Boolean))]
  }
}

// 下拉框选择事件处理
const handleStatusCategoryChange = (command: any) => {
  query.value.statusCategory = command
  search()
}

const handleProjectLeaderChange = (command: any) => {
  query.value.projectLeader = command
  search()
}

const handleProjectEmpIdChange = (command: any) => {
  query.value.projectEmpId = command
  search()
}

const handleBusinessTypeChange = (command: any) => {
  query.value.businessType = command
  search()
}

// 状态数字到文字的映射
const getStatusText = (status: string | number) => {
  const statusMap: { [key: string]: string } = {
    '0': '正常',
    '1': '诉讼',
    '2': '关注',
    '3': '终止',
    '4': '暂停'
  }
  return statusMap[status.toString()] || status
}
const getStatusType = (status: string | number) => {
  const statusT = getStatusText(status);
  switch (statusT) {
    case '正常':
      return 'success';
    case '诉讼':
      return 'danger';
    case '关注':
      return 'warning';
    case '终止':
      return 'info';
    case '暂停':
      return 'warning';
    default:
      return 'info';
  }
}









//抽屉
const drawer = ref(false)

//请求权限
interface RequestData {
  projectId: number
  projectName: string
  applicantId: number
  applicantName: string
  approverId: number
  approverName: string
  requestStatus: number
}

const requestData = ref<RequestData>({
  projectId: 0,
  projectName: '',
  applicantId: 0,
  applicantName: '',
  approverId: 0,
  approverName: '',
  requestStatus: 0,
})

//申请权限
// const Requestqx =async ( requestData:any)=>{
//     await Request(requestData.value)
//       console.log(requestData.value)
//       ElMessage.success('申请成功！')
// }

// 获取审批人信息
const getIDUser = ref<any[]>([]) // 明确指定为数组类型

const getApproval = async () => {
  try {
    const res = await getManagerId()
    console.log(res)
    if (res && res.data) {
      getIDUser.value = Array.isArray(res.data) ? res.data : [res.data]
    }
    console.log(getIDUser.value)
  } catch (error) {
    console.error('获取审批人信息失败:', error)
  }
}

// 在组件挂载时获取审批人信息
onMounted(() => {
  getApproval()
})

// console.log(getIDUser.value)
interface UserRoleResponse {
  code: string
  data: {
    roles: string[]
  }
}

const roles = ref<string>('')

async function getCheck() {
  try {
    const response = await request.get('/auth/user/info') as UserRoleResponse;
    console.log(response);
    roles.value = response.data.username;
    console.log(roles.value);
    // if (response.code === '0') {
    //   roles.value = userRoles[0];
    //   console.log(roles.value);

    // }
  } catch (error) {
    console.error('获取用户角色失败：', error);
    roles.value = 'user';
  }
}

//详情
const rowValue = ref({})

const Requestqx = async (data: any) => {
  try {
    await Request(data.value || data) // 兼容处理参数
    console.log('提交的数据:', data.value || data)
    ElMessage.success('申请成功！')
  } catch (error) {
    console.error('申请失败:', error)
    ElMessage.error('申请失败！')
  }
}

const drawe = async (row: any) => {
  drawer.value = true
  console.log(row);

  rowValue.value = toRaw(row);
  console.log(rowValue.value)

  await getCheck()

  // 确保审批人数据已加载
  if (!getIDUser.value || getIDUser.value.length === 0) {
    await getApproval()
  }

  // 从审批人数据中选择第一个作为默认审批人
  let approverId = 0
  let approverName = ''

  if (getIDUser.value && getIDUser.value.length > 0) {
    const firstApprover = getIDUser.value[0]
    approverId = firstApprover.id || 0
    approverName = firstApprover.name || firstApprover.username || ''
  }

  // 设置 requestData 的值
  requestData.value = {
    projectId: Number(rowValue.value.id) || 0,
    projectName: rowValue.value.projectName || '',
    applicantId: roles.value ? parseInt(roles.value) || 0 : 0,
    applicantName: roles.value || '',
    approverId: approverId,
    approverName: approverName,
    requestStatus: 0,
  }

  console.log('准备提交的数据:', requestData.value)
}




//   interface UserRoleResponse {
//   code: string
//   data: {
//     roles: string[]
//   }
// }

//   const roles = ref<string>('')

// async function getCheck() {
//   try {
//     const response = await request.get('/auth/user/info') as UserRoleResponse;
//     console.log(response);
//     const userRoles = response.data.roles;
//     if (response.code === '0') {
//       roles.value = userRoles[0];
//       console.log(roles.value);

//     }
//   } catch (error) {
//     console.error('获取用户角色失败：', error);
//     roles.value = 'user';
//   }
// }
// const Requestqx =async ( requestData:any)=>{
//     await Request(requestData.value)
//       console.log(requestData.value)
//       ElMessage.success('申请成功！')
// }



//分页器
const handleSizeChange = (pagesize: number) => {
  query.value.page = 1
  query.value.size = pagesize
  search()  // 使用search而不是GetData
}

const handleCurrentChange = (pagenumber: number) => {
  query.value.page = pagenumber
  search()  // 使用search而不是GetData
}

//新增
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogTableValue = ref({})

const isNull = (date: any) => {
  if (!date) return true
  if (JSON.stringify(date) === '{}') return true
  if (JSON.stringify(date) === '[]') return true
}

const handleDialogValue = (row: any) => {
  if (isNull(row)) {
    dialogTitle.value = '添加项目'
    dialogTableValue.value = {}
  } else {
    dialogTitle.value = '编辑项目'
    dialogTableValue.value = JSON.parse(JSON.stringify(row))
  }
  dialogVisible.value = true
}



//删除
const Del = (row: any) => {
  ElMessageBox.confirm(
    'Warning',
    {
      confirmButtonText: 'OK',
      cancelButtonText: 'Cancel',
      type: 'warning',
    }
  )
    .then(async () => {
      await onDelete(row.id)
      ElMessage({
        type: 'success',
        message: 'Delete completed',
      })
      GetData()
      console.log(row)
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Delete canceled',
      })
    })
}



</script>

<style scoped>
.card {
  border: none;
}

.tz {
  /* width: 100vh; */
  width: 1650px;
  height: 963px;
  background-color: #F6F8FC;
}

.hd {
  display: flex;
  flex-direction: row;
}

.xm {
  width: 87px;
  height: 30px;
  margin: 5px;
  color: #1A70AD;
  border-left: #36A46E solid 5px;
  padding-left: 5px;
  padding-top: 3px;
  margin-left: 20px;
}

.xz {
  width: 150px;
  height: 40px;
  color: #fff;
  background-color: #36A46E;
  text-align: center;
  /* padding-top: 8px; */
  border-radius: 5px;
  border: none;
  box-shadow: 3px 3px 6px rgba(0, 0, 0, 0.5);
  margin-left: 50px;
}

.zs {
  width: 1620px;
  height: 887px;
  background-color: #fff;
  border-radius: 5px;
}

.table {
  width: 1580px;
  height: 648px;
  /* background-color: #6e94e5; */
  margin: 0 auto;
}

hr {
  margin-left: 20px;
  margin-right: 20px;
  color: #1A70AD;
  size: 4px;
}

:deep(.el-drawer_rtl_open) {
  width: 50%;
}

.ts {
  padding: 20px;
}

.block {
  display: flex;
  flex-direction: row;
  /* padding: 30px 0; */
  border-right: solid 1px var(--el-border-color);
  /* flex: 1; */
  /* background-color: #972d2d; */
  justify-content: space-between;
  margin-top: 23px;
  margin-left: 20px;
  margin-right: 50px;
  padding-bottom: 24px;
  border-right: none;
  border-bottom: #1A70AD solid 1px;
}

:deep(projectName) {
  width: 475px;
  /* height: 50px; */
}

:deep(.el-date-picker) {
  margin-left: 20px;
}

:deep(.el-button.time) {
  background-color: #1A70AD;
  color: #fff;
  border: none;
}

:deep(.el-button) {
  width: 251px;
  /* height: 50px; */
  margin-left: 25px;
  color: rgba(0, 0, 0, 0.3);
}

.el-icon--right {
  color: #1A70AD;
}

.el-select__wrapper {
  width: 251px;
  text-align: center;
}





.block {
  display: flex;
  flex-direction: row;
  /* padding: 30px 0; */
  border-right: solid 1px var(--el-border-color);
  /* flex: 1; */
  /* background-color: #972d2d; */
  justify-content: space-between;
  margin-top: 23px;
  padding-bottom: 24px;
  border-right: none;
  border-bottom: #1A70AD solid 1px;
}

:deep(projectName) {
  width: 475px;
  height: 50px;
}

:deep(.el-date-picker) {
  margin-left: 20px;
}

:deep(.el-button.time) {
  background-color: #1A70AD;
  color: #fff;
  border: none;
}

:deep(.el-button) {
  width: 251px;
  height: 30px;
  margin-left: 25px;
  color: rgba(0, 0, 0, 0.3);
}

.el-icon--right {
  color: #1A70AD;
}




:deep(.el-table th) {
  height: 50px;
  color: #fff;
  text-align: center;
  padding: 0;
  border: solid 1px #36A46E;
}

:deep(.el-table tr) {
  height: 50px;
  color: #1A70AD;

}

:deep(.el-table-column) {
  text-align: center;

}

:deep(.el-table .sort-caret.descending) {
  border-top-color: #fff;
}

:deep(.el-table .sort-caret.ascending) {
  border-bottom-color: #fff;
}

:deep(.el-table .cell) {
  /* border: solid 1px #36A46E; */
  padding: 0;
}

:deep(.el-table .el-table__cell) {
  text-align: center;
  border: solid 1px #36A46E;
}

.page {
  display: flex;
  justify-content: flex-end;
  margin-top: 5px;
}


.tit {
  width: 130px;
  height: 30px;
  font-size: 18px;
  text-align: center;
  justify-content: center;
  padding-top: 5px;
  color: #1A70AD;
  border-bottom: #1A70AD solid 3px;
}

.h {
  border-bottom: #E2E7F5 solid 1px;
  margin-bottom: 16px;
}

.in {
  width: 267px;
  height: 50px;
  border: #E2E7F5 solid 1px;
  margin-left: 25px;
}

input {
  width: 267px;
  height: 50px;
  border: #E2E7F5 solid 1px;
  margin-left: 25px;
}

.i1 {
  width: 267px;
  height: 50px;
  border: #E2E7F5 solid 1px;
  margin-left: 5px;
}

.i3 {
  width: 267px;
  height: 50px;
  border: #E2E7F5 solid 1px;
  margin-left: 45px;
}

.i2 {
  width: 230px;
  height: 50px;
  border: #E2E7F5 solid 1px;
  margin-left: 20px;
}

.fle {
  width: 1900px;
  /* display: flex; */
  /* justify-content: space-around; */
  /* flex-wrap: wrap; */
}

.de {
  width: 400px;
  height: 50px;
  border-left: #1A70AD solid 5px;
  margin-bottom: 12px;
  font-size: 20px;
  /* margin-right: 30px; */
  padding-left: 5px;
  display: flex;
  flex-direction: row;
}

.de1 {
  width: 739px;
  /* border-left: #1A70AD solid 5px; */
  font-size: 20px;
  display: flex;
  flex-direction: row;
}

textarea {
  width: 789px;
  height: 80px;
}

.action {
  display: flex;
  flex-direction: row;
  height: 20px;
  width: 20px;
}

.card {
  display: flex;
  flex-direction: row;
}

.label {
  display: block;
}

/* :deep(.el-table--enable-row-transition .el-table__body td.el-table__cell){
  padding: 0;
} */

:deep(.el-table .cell) {
  box-sizing: border-box;
  line-height: 30px;
  white-space: normal;
  overflow: visible;
}



/* 在样式部分添加或修改 */
.page {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding: 20px;
  background-color: #fff;
}

:deep(.el-pagination) {
  padding: 0;
}

:deep(.el-pagination .el-pagination__total) {
  color: #606266;
}

:deep(.el-pagination .el-pagination__jump) {
  color: #606266;
}

:deep(.el-pagination .el-input__inner) {
  height: 28px;
}
</style>